﻿using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Collections;
using System.Data;
using System.ComponentModel;
using System.Data.OracleClient;
using WPFExcelReport.Helpers;
using WPFExcelReport.Controls;
using System.Collections.Generic;
using ReflectionStudio.Core.Events;
using System;
using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
namespace WPFExcelReport
{
    /// <summary>
    /// 根据品种编号搜索所有需求，并自动进行累计
    /// 选择进入需要创建采购单或生产单队列，
    /// 创建生产单
    /// 创建留位关系
    /// </summary>
    public partial class TPRWD02
    {
     
        public TPRWD02()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VWDECK();
            DataContext = MV;
            InitializeComponent();
            IsShowAll = true;
        }

        public override void vwMaster_CurrentChanged(object sender, EventArgs e)
        {
            base.vwMaster_CurrentChanged(sender, e); 
            if(dwMaster!=null)
            {
                INFO = dwMaster["VKPART"].ToString().Trim();
                if (dwMaster["VKPART"].ToString().Trim()!= dwMaster["WDART"].ToString().Trim())
                {
                    INFO = "出现了品种不一致" + dwMaster["VKPART"].ToString().Trim()
                        + "," + dwMaster["WDART"].ToString().Trim() + dwMaster["WDAUFKRS"].ToString().Trim() + dwMaster["WDAUFLFD"].ToString().Trim() + dwMaster["WDAUFPOS"].ToString().Trim() + "，请立即通知管理员";
                    MessageBox.Show(INFO);
                }
            }
        }

        public override void OnKDBLOCKChg(bool value)
        {


        }
        public override void OnVKBLOCKChg(string value)
        {
            if (value.Length < 9)
                return;
            vwMaster.View.MoveCurrentTo(-1);
            filter = "WDSA='" + value.Substring(0, 1) + "' AND WDAUFKRS='" + value.Substring(1, 2) + "' AND WDAUFLFD>='" + value.Substring(3, 6) + "'";
            rows = TBMain.Select(filter);
            foreach (DataRow row in rows)
            {
                row.Delete();
            }
            TBMain.AcceptChanges();
            base.OnVKBLOCKChg(value);
        }
        /// <summary>
        /// 1. 手工插入需求行
        /// 2.插入完成后，转入完成模式
        /// </summary>

        public void InsertCommand(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!IsInsertManually)
            {
                IsInsertManually = true;
                LFD = VSDDAT.SD22.GETNEXT("0022", "WB", "WDAUF", 1);
                INFO = "直到本次输入完成需要计划的所有品种完成，然后点击后面的完成";
                //return;
            }
            dwData = TBMain.NewRow();
            TMV.SetUpNewRow(ref dwData);
            dwData["WDMANDANT"] = app.Mandant;
            dwData["AUFTYP"] = "M";
            dwData["WDAUFKRS"] = "WB";
            dwData["WDAUFLFD"] = LFD;
            POS = VSDDAT.SD22.GETNEXT("0022", "WB", LFD, 1);
            dwData["WDAUFPOS"] = Helpers.Helper.Right(POS, 3);
            dwData["WDUPOS"] = "01";
            dwData["VKPBSTSTA"] = 70;
            TBMain.Rows.InsertAt(dwData, 0);
            vwMaster.View.MoveCurrentToFirst();
            base.NewCommand(sender, e);
        }
        public override void OnPARTIEChg()
        {
            if (PARTIE == "")
                return;
            dwData = TBMain.Clone().NewRow();
            dwData["WDMANDANT"] = app.Mandant;
            dwData["WDSA"] = AUFART;
            dwData["WDTYP"] = "B"; 
            dwData["WDBEDST"] = " AND WDAUFKRS='" +PARTIE.Substring(0,2)+ "' AND WDAUFLFD='00"+ PARTIE.Substring(2, 4)+ "' AND WDAUFPOS='"+ PARTIE.Substring(7, 3)+"' AND WDART='"
                +PARTIE.Substring(20,20)+"'" +" AND WDFARBE='" + PARTIE.Substring(40, 10)+"'";
             
            SResult = TMV.QWD261(dwData);
            MergeData(SResult, true);
            if (TBMain.Rows.Count > 0)
                return;
            dwData = TBMain.Clone().NewRow();
            dwData["WDMANDANT"] = app.Mandant;
            dwData["WDSA"] = AUFART;
            dwData["WDTYP"] = "B";
            dwData["WDBEDST"] = " AND WDART='" + PARTIE.Substring(20, 20) + "'" + " AND WDFARBE='" + PARTIE.Substring(40, 10) + "'";
            SResult = TMV.QWD261(dwData);
            MergeData(SResult, true);
            base.OnPARTIEChg();
        }
        public override void QueryCommand(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                dwData = TBMain.Clone().NewRow();
                dwData["WDMANDANT"] = app.Mandant;
                dwData["WDSA"] = AUFART;
                dwData["WDTYP"] = "B";
                dwData["WDART"] = ART.Trim();
                dwData["WDFARBE"] = FARBE.Trim();
                //dwData["WDBEDST"] = " AND VKKVB='" + VB + "'";
                dwData["WDAUFKRS"] = " AND WDAUFKRS LIKE '%" + KRS.Trim() + "%'";
                dwData["WDAUFLFD"] = " AND WDAUFLFD LIKE '%" + LFD.Trim() + "%'";
                dwData["WDAUFPOS"] = " AND WDAUFPOS LIKE '%" + POS.Trim() + "%'";
                if (!IsShowAll)
                {
                    dwData["WDBEDST"] = " AND (P.WDBEDARF - P.WDZUGET - P.WDRESERV > 0) ";
                }
                SResult = TMV.QWD261(dwData);
                MergeData(SResult, false);
                IsVKPaid = !IsVKPaid;
                IsVKPaid = !IsVKPaid;
                base.QueryCommand(sender, e);
                TBDetail.Clear();
                TBDetail.Merge(TBMain.Clone());
                vwDetail.Source = TBDetail;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public override void OnPaidOnly(bool value)
        {
            if (!IsLoaded)
                return;
            if (vwMaster.View == null)
            {
                return;
            }
            if (value)
            {

                cvMaster.CustomFilter = "VKPBSTSTA='70' ";
            }
            else
            {
                cvMaster.CustomFilter = null;
            }
            base.OnPaidOnly(value);
        }
        /// <summary>
        /// 选择品种
        /// </summary>
        /// <param name="_dwVF"></param>
        public override void OnVAFChg(DataRow _dwVF)
        {
            if (!IsEdit)
                return;
            if (_dwVF == null)
                return;
            if (dwMaster == null)
                return;
            dwMaster["WDART"] = _dwVF["VAFPART"];
            dwMaster["WDVAR"] = _dwVF["VAFPVAR"];
            dwMaster["WDFARBE"] = _dwVF["VAFFFARBE"];

            dwMaster["WDBESCHICH"] = _dwVF["VAFBESCHICH"].ToString();
            dwMaster["WDDESS"] = _dwVF["VAFDESS"].ToString();
            dwMaster["WDCOLORIT"] = _dwVF["VAFCOLORIT"].ToString();

        }

        public void RemoveBundlesCommand(object sender, RoutedEventArgs e)
        {  
            dwData = TMV.VPR.TBMain.NewRow();
            TMV.VPR.SetUpNewRow(ref dwData);
            dwData["P4"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDUPOS"].ToString() + "K";
            SResult = TMV.VPR.QPRULES06(dwData);
            foreach(DataRow row in SResult.Tables[0].Rows)
            {
                PM["KRS"] = row["P4"].ToString().Substring(0, 2);
                PM["LFD"] = row["P4"].ToString().Substring(2, 6);
                PM["POS"] = row["P4"].ToString().Substring(8, 3);
                dwData["ORDERNUM"] = row["ORDERNUM"];
                TMV.DVKPON(PM);
            } 
            TMV.VPR.DPRULES03(dwData);
            BNDABP = "";
            cvMaster.CustomFilter = null;
            MessageBox.Show("合并生产被完全解除，请重新开始");
        }
        string basearticle = "";
        string CART = "";
        /// <summary>
        /// //首先判断此单是否已经创建了生产单，提示删除
        ///首先判断此单是否已经创建了生产单，提示删除,进入何并生产模式,产生生产单号码,下一个使用相同单号,创建完成后，解除何并模式
        ///产生生产单号码
        ///下一个使用相同单号
        ///创建完成后，解除何并模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void AppendBundlesCommand(object sender, RoutedEventArgs e)
        {
            try
            {
                bool IsNew = true;

                if (ABKRS == "")
                {
                    throw new Exception("请先定义生产单前缀");
                }
                if (BNDABP == "")
                {
                    IsOnBundleMode = false;
                }
                  
                if (!IsOnBundleMode)
                {
                    TBDetail.Clear();
                    BNDABP = "";
                    QTY = 0;
                    IsOnBundleMode = true;
                    string KDAUFTNR = dwMaster["WDAUFKRS"].ToString() + dwMaster["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString();
                    basearticle = dwMaster["WDWAKZ"].ToString() + dwMaster["WDART"].ToString() + dwMaster["WDVAR"].ToString()
                    + dwMaster["WDFARBE"].ToString() + dwMaster["WDBESCHICH"].ToString()
                     + dwMaster["WDDESS"].ToString() + dwMaster["WDCOLORIT"].ToString();
                    cvMaster.CustomFilter = "WDART='" + TMV.WDART + "' AND WDVAR='"
                        + TMV.WDVAR + "' AND WDFARBE='" + TMV.WDFARBE + "' AND WDBESCHICH='" + TMV.WDBESCHICH + "' AND WDDESS='" + TMV.WDDESS + "' AND WDCOLORIT='" + TMV.WDCOLORIT + "'";
                    if (ABAUF == "")
                    {
                        PM["RUNID"] = this.RUNID;
                        PM["KRS"] = ABKRS;
                        PM["LFD"] = dwWD["WDAUFLFD"].ToString();
                        PM["AUFART"] = AUFART;
                        PM["ORDERNUM"] = KDAUFTNR;
                        PM["RELOADABK"] = false;
                        ABAUF = TMV.VABK.NEWABK(PM);
                    }
                    RUNID = this.RUNID;
                    PM["KRS"] = ABAUF.Substring(0, 2);
                    PM["LFD"] = ABAUF.Substring(2, 6);
                    PM["AUFART"] = "VA";
                    PM["ORDERNUM"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString();
                    TMV.VABK.LOAD(PM);
                    dwMaster["KRS"] = ABAUF.Substring(0, 2);
                    dwMaster["LFD"] = ABAUF.Substring(2, 6);
                    //POS = VSDDAT.SD22.GETNEXT("0022", ABKRS, ABAUF.Substring(0, 8), 1);
                    dwMaster["POS"] = dwWD["WDAUFPOS"].ToString();
                    ABAUF += dwWD["WDAUFPOS"].ToString();
                    PM["RUNID"] = RUNID;
                    PM["CART"] = dwWD["WDART"].ToString() + dwWD["WDVAR"].ToString() + dwWD["WDFARBE"].ToString() + dwWD["WDBESCHICH"].ToString() + dwWD["WDDESS"].ToString() + dwWD["WDCOLORIT"].ToString();
                    PM["VKPAUF"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDUPOS"].ToString() + "K";
                    PM["VKAUF"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDUPOS"].ToString() + "K";

                    PM["ARTSTAGE"] = "F";
                    PM["DELDATE"] = dwRule["DELDATE"].ToString();
                    PM["VKPQTY"] = dwRule["QTYEND"].ToString();
                    PM["ORDERNUM"] = dwWD["KRS"].ToString() + dwWD["LFD"].ToString() + dwWD["POS"].ToString() + "VA ";
                    BNDABP = dwWD["KRS"].ToString() + dwWD["LFD"].ToString() + dwWD["POS"].ToString() + "VA ";
                    PM["COLOR"] = "VA ";
                    PM["AUFTYP"] = "V";
                    PM["QTYEND"] = double.Parse(dwRule["QTYMAT"].ToString());
                    PM["P7"] = PM["DELDATE"];//VKDELDATE
                    dwData = TMV.VPR.TBMain.NewRow();
                    TMV.VPR.SetUpNewRow(ref dwData);
                    PM["P4"] = PM["VKAUF"];
                    PM["P5"] = PM["VKPAUF"];
                    PM["P10"] = dwWD["WAFZUART"].ToString();
                    foreach (DataColumn cm in dwData.Table.Columns)
                    {
                        string cname = cm.ColumnName;
                        if (cname == "ROWNID") continue;
                        if (PM.Keys.Contains(cname))
                        {
                            dwData[cname] = PM[cname].ToString();
                        }
                    }
                    SResult = TMV.VPR.QPRULES05(dwData);
                    foreach(DataRow row in SResult.Tables[0].Rows)
                    {
                        IsNew = false;
                        dwData["ROWNID"] = row["ROWNID"];
                        TMV.VPR.DPRULES01(row);
                    }
                    if(IsNew)
                    {
                        dwData["ROWNID"] = VSDDAT.SD22.GETNEXT("0022", "PR", "  ", 1, 10);
                    }
                    TMV.VPR.InsertICC_PRULES(dwData);
                }
                else
                {
                    CART = dwMaster["WDWAKZ"].ToString() + dwMaster["WDART"].ToString() + dwMaster["WDVAR"].ToString()
                    + dwMaster["WDFARBE"].ToString() + dwMaster["WDBESCHICH"].ToString()
                     + dwMaster["WDDESS"].ToString() + dwMaster["WDCOLORIT"].ToString();
                    if (CART != basearticle)
                    {
                        throw new Exception("品种不一致，不可以合并生产");
                    }
                    PM["ORDERNUM"] = BNDABP;
                    SResult = TMV.VPR.LOAD(PM);
                    DataRow dwBRule = null;
                    ///增加生产单数量
                    foreach (DataRow row in SResult.Tables[0].Copy().Rows)
                    {
                        dwBRule = row;
                        dwBRule["QTYEND"] = double.Parse(dwRule["QTYMAT"].ToString()) + double.Parse(dwBRule["QTYEND"].ToString());
                        TMV.VPR.UPRULES02(dwBRule);
                    }
                    if (dwBRule == null)
                        return;
                    dwData = dwBRule.Table.NewRow();
                    dwData.ItemArray = dwBRule.ItemArray;
                    
                    PM["CART"] = dwWD["WDART"].ToString() + dwWD["WDVAR"].ToString() + dwWD["WDFARBE"].ToString() + dwWD["WDBESCHICH"].ToString() + dwWD["WDDESS"].ToString() + dwWD["WDCOLORIT"].ToString();
                    PM["VKPAUF"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDUPOS"].ToString() + "K";
                    PM["VKAUF"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDUPOS"].ToString() + "K";
                    PM["ARTSTAGE"] = "F";
                    PM["DELDATE"] = dwRule["DELDATE"].ToString();
                    PM["VKPQTY"] = dwRule["QTYEND"].ToString();
                    PM["ORDERNUM"] = BNDABP;
                    PM["COLOR"] = "VA ";
                    PM["AUFTYP"] = "V";
                    PM["P7"] = PM["DELDATE"];//VKDELDATE
                    PM["P4"] = PM["VKAUF"];
                    PM["P5"] = PM["VKAUF"];
                    PM["P10"] = dwWD["WAFZUART"].ToString();
                    foreach (DataColumn cm in dwData.Table.Columns)
                    {
                        string cname = cm.ColumnName;
                        if (cname == "ROWNID") continue;
                        if (PM.Keys.Contains(cname))
                        {
                            dwData[cname] = PM[cname].ToString();
                        }
                    }
                    SResult = TMV.VPR.QPRULES05(dwData); 
                    foreach (DataRow row in SResult.Tables[0].Rows)
                    {
                        IsNew = false;
                        dwData["ROWNID"] = row["ROWNID"];
                        TMV.VPR.DPRULES01(row);
                    }
                    if (IsNew)
                    {
                        dwData["ROWNID"] = VSDDAT.SD22.GETNEXT("0022", "PR", "  ", 1, 10);
                    }
                    TMV.VPR.InsertICC_PRULES(dwData);
                    QTY = double.Parse(dwBRule["QTYEND"].ToString());
                } 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void BundlesCommand(object sender, RoutedEventArgs e)
        {
            IsOnBundleMode = false;
            //找到原来的单的信息，更改订单量，发布创建消息
            dwData = TMV.VPR.TBMain.NewRow();
            dwData["ORDERNUM"] = BNDABP;//目标销售单
            SResult = TMV.VPR.QPRULES02(dwData);
            DataRow dwBRule = null;
            foreach (DataRow row in SResult.Tables[0].Copy().Rows)
            {
                dwBRule = row;
                break;
            }
            if (dwBRule == null)
                return;

            string KDAUFTNR = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString();
           
            RUNID = this.RUNID;
            PM["KRS"] = ABAUF.Substring(0, 2);
            PM["LFD"] = ABAUF.Substring(2, 6);
            PM["AUFART"] = "VA";
            PM["ORDERNUM"] = dwBRule["ORDERNUM"].ToString().Substring(0, 11);
            TMV.VABK.LOAD(PM);
            dwWD["KRS"] = BNDABP.Substring(0, 2);
            dwWD["LFD"] = BNDABP.Substring(2, 6);
            dwWD["POS"] = BNDABP.Substring(8, 3);
            PM["RUNID"] = RUNID;
            //根据不同点的原料类型，需求创建不同的订单
            //在创建时，决定使用现有库存还是新订单 
            if (dwWD == null)
                return;
            PM["ORDERNUM"] = dwWD["WDAUFKRS"].ToString() + dwWD["WDAUFLFD"].ToString() + dwWD["WDAUFPOS"].ToString() + dwWD["WDSA"].ToString() + dwWD["WDUPOS"].ToString();
            //销售单规则已经创建好，这里捕捉实际值，并保存规则
            if (dwBRule == null)
                return;
            MessageInfo msg = new MessageInfo();
            #region===产生首个计划规则，传递参数======
            msg = new MessageInfo();
            msg.AUFTYP = "K";
            msg.WAKZ = dwWD["WDWAKZ"].ToString();
            msg.ART = dwWD["WDART"].ToString();
            msg.VAR = dwWD["WDVAR"].ToString();
            msg.FARBE = dwWD["WDFARBE"].ToString();
            msg.BESCHICH = dwWD["WDBESCHICH"].ToString();
            msg.DESS = dwWD["WDDESS"].ToString();
            msg.COLORIT = dwWD["WDCOLORIT"].ToString();
            msg.BESCHICH = dwWD["WDBESCHICH"].ToString();
            msg.DESS = dwWD["WDDESS"].ToString();
            msg.COLORIT = dwWD["WDCOLORIT"].ToString();
            msg.KRS = dwWD["WDAUFKRS"].ToString();
            msg.LFD = dwWD["WDAUFLFD"].ToString();
            msg.POS = dwWD["WDAUFPOS"].ToString();
            msg.P1 = dwWD["WDUPOS"].ToString();
            msg.P2 = dwWD["WDSA"].ToString();
            msg.Where = app.User;
            msg.Sender = this.RUNID;
            msg.MSGTYPE = "RZABPNEW";
            msg.ACTION = "RZABPNEW";
            #endregion 
            msg.P3 = "F";
            msg.ORDER = BNDABP;
            VICC_WFEVENTS.SVWF.CheckEvents("UIMESSAGE", null, "", msg);
        }

        public  void SendMessage()
        { 
            MessageInfo msg = new MessageInfo(); 
            PRART = "F"+ART + VAR.PadRight(3) + FARBE.PadRight(10) + FINISH.PadRight(10) + DESS.PadRight(10) + COLORIT.PadRight(10);
            msg.Sender = this.RUNID;
            msg.MSGTYPE = "RZABPNEW";
            msg.ACTION = "RZABPNEW";
            msg.AUFTYP = "V";
            msg.WAKZ = "F";
            msg.ART = TMV.ART;
            msg.VAR =TMV.VAR;
            msg.FARBE =TMV.FARBE;
            msg.BESCHICH =TMV.FINISH;
            msg.DESS = TMV.DESS;
            msg.COLORIT =TMV.COLORIT;
            msg.ORDER = (string)PM["ORDERNUM"];
            msg.Where = app.User;
            VICC_WFEVENTS.SVWF.CheckEvents("UIMESSAGE", null, "", msg); 
        }
        public   void ManualCreateCommand(object sender, RoutedEventArgs e)
        {
            New();
            base.NewCommand(sender, e);
        }
        public override void New()
        {
            try
            { 
                PRART = "F" + ART + VAR.PadRight(3) + FARBE.PadRight(10) + FINISH.PadRight(10) + DESS.PadRight(10) + COLORIT.PadRight(10); 
                if (ABKRS == "")
                {
                    throw new Exception("前缀");
                } 
                if (FLOW == "")
                {
                    throw new Exception("流程");
                }
                string krs = "M" + ABKRS.Substring(1, 1);
                TBMain.Clear();
                dwData = TBMain.NewRow(); 
                PM["RUNID"] = this.RUNID;
                PM["KRS"] = krs;
                PM["AUFART"] = "VA";
                PM["ORDERNUM"] = TMV.date;
                PM["RELOADABK"] = false;
                string ABAUF = TMV.VABK.NEWABK(PM);
                LFD = ABAUF.Substring(2, 6);
                POS = VSDDAT.SD22.GETNEXT("0022", krs, LFD, 1, 3);
                PM["ORDERNUM"] = krs + LFD + POS + "VA ";
                PM["COLOR"] = "VA ";
                PM["AUFTYP"] = "V";
                PM["ARTSTAGE"] = "Z";
                PM["P4"] = "".PadRight(12);
                PM["VKPAUF"] = KRS + LFD + POS;
                PM["VKPQTY"] = 0;//
                PM["VKAUF"] = "                  ";//
                PM["UNDES"] = FLOW;
                PM["DELDATE"] = TMV.date;
                PM["STARTDATE"] = TMV.date;
                TMV.VPR.NEWPLAN(PM);  
                SendMessage();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            } 
        }

    }
}
